﻿/*
 * Creato da SharpDevelop.
 * Utente: Ciccio
 * Data: 13/07/2008
 * Ora: 11.11
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System.Data;
using System.Web;
using System;
using ACM.cmsarea08.Administration;

namespace ACM.cmsarea08.Administration.Core
{
	/// <summary>
	/// Description of Class1.
	/// </summary>
	public class AdminMenuGenerator
	{
		private static AdminMenuGenerator _istanza=null;
		private static object locker = new object();
		private ACM.cmsarea08.Administration.Core.DBClass dclass;
		private const string common_folder = "/administration/template/admimg/";
		private DataSet _myadminMenu = null;
		public static AdminMenuGenerator adminMenu {
			get {
				if(_istanza==null) {
					lock(locker) { _istanza = new AdminMenuGenerator(); }
				}
				return _istanza;
			}
		}
		
		public DataSet AdminMenu {
			get {
				if(HttpContext.Current.Session==null) {
					return _myadminMenu;
				}
				object mymenu = HttpContext.Current.Session["myAdminMenu"];
				if(mymenu == null) return null;
				if(mymenu is DataSet) return (DataSet)mymenu;
				return null;
			}
			set {
				if(HttpContext.Current.Session!=null) 
					HttpContext.Current.Session["myAdminMenu"] = value;
				else
					_myadminMenu = value;
			}
		}
		
	
		
		#region costanti_query
			const string bMenu_lingua = "select distinct * from {0}admin_menu " +
			                          "where enabled='1' and (lingua='{1}' or lingua='') order by figliodi,ordine ;";
			const string bMenu_linguaruoli = "select distinct * from {0}admin_menu " +
			                          "where enabled='1' and (lingua='{1}' or lingua='') and ({2}) order by figliodi,ordine ;";
			const string bUserRules = "select distinct " +
				"cast(uroles.role as char) as `role`," +
				"cast(uroles.relatedto as char) as `relatedto`, " +
				"cast(uroles.admin_menu as char) as `admin_menu`," +
				"cast(uroles.position  as char) as `position`," +
				"cast(uroles.id as char) as `id`, " +
				"cast(uroles.order  as char) as `order`," +
				"cast(uroles.sonof as char) as `sonof`," +
				"cast(uroles.operation  as char) as `operation`," +
				"cast(uroles.nomevoce  as char) as `nomevoce`," +
				"cast(uroles.lang as char) as `lang`, " +
				" cast(if(avoice.link is null,'#',avoice.link) as char)  as av_link ," +
				" cast(if(avoice.ruolo is null,uroles.relatedto,avoice.ruolo) as char)  as av_ruolo," +
				" cast(if(avoice.enabled is null, '1',avoice.enabled) as char)  as av_enabled," +
				" cast(if(avoice.figliodi is null,uroles.sonof,avoice.figliodi) as char)  as av_figliodi, " +
				" cast(if(avoice.ordine is null, uroles.order,avoice.ordine) as char)  as av_ordine, " +
				" cast(if(avoice.target is null,'_self',avoice.target) as char)  as av_target," +
				" cast(if(avoice.lingua is null,uroles.lang, avoice.lingua) as char)  as av_lingua ," +
				" cast(if(avoice.id_component is null,'-1',avoice.id_component) as char)  as av_id_component , " +				
				" cast(if(avoice.nome is null,uroles.nomevoce,avoice.nome) as char)  as av_nome , " +
				" cast(if(avoice.urlimg is null,'',avoice.urlimg) as char)  as av_urlimg, " +
				" cast(if(avoice.id_instance is null,'-1',avoice.id_instance) as char)  as av_id_instance," +
				" cast(if(avoice.name_group is null,'',avoice.name_group) as char)  as av_name_group, " +
				" cast(if(avoice.link is null,'1','0') as char) as customME " +
                " from {0}user_menu as uroles " +
				" left join {0}admin_menu as avoice on uroles.admin_menu = avoice.id and uroles.lang=avoice.lingua and avoice.enabled='1' " +
                " where uroles.relatedto='{1}' and uroles.position='top' and uroles.role='group' and (uroles.lang='{2}' or uroles.lang='') " +
				" order by uroles.sonof  ";
			
		
				
		#endregion
		
		
		
		public AdminMenuGenerator()
		{
			dclass= new Administration.Core.DBClass();
		}
		/// <summary>
		/// Metodo base per ottenere il menu amministrativo completo.
		/// </summary>
		/// <param name="lingua"></param>
		/// <returns>DataSet con il Menu</returns>
		public DataSet getBaseMenu(string lingua) {
			string lang =(lingua.Trim()==""?mainconfiguration.MainConf.LinguaPredefinita:lingua);;
			DataSet ds=new DataSet();
			ds = dclass.ExecuteDataset(string.Format(bMenu_lingua,dclass.TablePrefix,lang));
			return ds;
		}
		/// <summary>
		/// metodo base per ottenere il menu amministrativo in funzione dei ruoli, non tiene conto
		/// delle customizzazioni
		/// </summary>
		/// <param name="lingua">lingua corrente dell'utente</param>
		/// <param name="roles">matrice di stringhe con i ruoli da caricare</param>
		/// <returns>DataSet con il menu</returns>
		public DataSet getBaseMenu(string lingua, string[] roles) {
			string lang =(lingua.Trim()==""?mainconfiguration.MainConf.LinguaPredefinita:lingua);
			string ruoli = "";
			for(int i = 0 ; i<roles.Length; i++) 
				ruoli += " instr(ruolo, '"+roles[i]+"')>0 or";
			if(ruoli.EndsWith("or"))
				ruoli = ruoli.Substring(0, ruoli.Length-2);			
			
			DataSet ds=new DataSet();
			ds = dclass.ExecuteDataset(string.Format(bMenu_linguaruoli,
			                                         dclass.TablePrefix,lang,ruoli));
			return ds;
		}		
		
		public DataSet getCustomMenu(string lingua, string[] roles ) {
			string lang = (lingua.Trim()==""?mainconfiguration.MainConf.LinguaPredefinita:lingua);
			string exquery = "";
			if(roles.Length==1) 
				exquery = string.Format(bUserRules, dclass.TablePrefix, roles[0],lang) + ";";
			else {
				exquery = "";
				for(int i = 0 ; i <roles.Length; i++) {
					exquery += "("  + string.Format(bUserRules, dclass.TablePrefix, roles[i],lang) + " ) UNION ";
				}
				exquery = exquery.Trim();
				exquery = exquery.Substring(0, exquery.Length- ("UNION").Length) + ";";
			}
			DataSet ds=new DataSet();
			try {
				//HttpContext.Current.Response.Write("<hr/>" + exquery); 
				ds = dclass.ExecuteDataset(exquery);
			} catch (Exception ex) {
				HttpContext.Current.Response.Write("ERRORE : " + ex.ToString() + "<hr/>" + exquery); 
			}
			return ds;
		}
		
		private void CleanSons(string id, DataSet ds) {
			DataRow[] drs = ds.Tables[0].Select("figliodi='" + id +"'");
			for(int i=0; i<drs.Length; i++) {
				CleanSons(drs[i]["id"].ToString(), ds);
				ds.Tables[0].Rows.Remove(drs[i]);
			}
			return;
		}
		
		private void TryForSons(DataSet customMenu, DataTable dt, string idpadre,string lingua) {
			DataRow[] menuSons = customMenu.Tables[0].Select("operation='A' and sonof='"+idpadre+"' ");
			if(menuSons!=null && menuSons.Length>0) {
				for(int f =0; f<menuSons.Length; f++) {
					DataRow drf = dt.NewRow();
					drf["id"] = idpadre + "_"+(menuSons[f]["customME"].ToString()=="0" &&
					             menuSons[f]["id"].ToString()=="-1"
					             ?menuSons[f]["admin_menu"]:("C"+menuSons[f]["id"].ToString()));
					drf["link"] =menuSons[f]["av_link"];
					drf["ruolo"] =menuSons[f]["av_ruolo"];
					drf["enabled"] =menuSons[f]["av_enabled"];
					drf["figliodi"] =idpadre;
					drf["ordine"] =menuSons[f]["av_ordine"];
					drf["target"] =menuSons[f]["av_target"];
					drf["lingua"] =(menuSons[f]["av_lingua"]==null || 
					                menuSons[f]["av_lingua"].ToString().Trim()=="" 
					                ?lingua:menuSons[f]["av_lingua"]);
					drf["id_component"] =menuSons[f]["av_id_component"];
					drf["urlimg"] =(menuSons[f]["av_urlimg"]==null || 
					                menuSons[f]["av_urlimg"].ToString().Trim()=="" 
					                ?"":menuSons[f]["av_urlimg"]);
					drf["id_instance"] =menuSons[f]["av_id_instance"];
					drf["name_group"] =(menuSons[f]["av_name_group"]==null || 
					                menuSons[f]["av_name_group"].ToString().Trim()=="" 
					                ?"":menuSons[f]["av_name_group"]);
//					drf["nome"] =(menuSons[f]["customME"].ToString()=="0" && 
//					              menuSons[f]["id"].ToString()=="-1"
//					              ?menuSons[f]["av_nome"]:(menuSons[f]["nomevoce"].ToString()));
					if(menuSons[f]["operation"].ToString()=="A") {
						drf["nome"] = (menuSons[f]["nomevoce"].ToString().Trim()==""?
						               menuSons[f]["av_nome"]:(menuSons[f]["nomevoce"].ToString()));
					} else {
						drf["nome"] =(menuSons[f]["customME"].ToString()=="0" && 
					              menuSons[f]["id"].ToString()=="-1"
					              ?menuSons[f]["av_nome"]:(menuSons[f]["nomevoce"].ToString()));
					}					
					
					drf["customVoce"] =true;
					dt.Rows.Add(drf);
					TryForSons(customMenu, dt, drf["id"].ToString(),lingua);
				}
			}			
		}
		public DataSet ApplyCustomMenu(DataSet baseMenu, DataSet customMenu,string lingua) {
			if(baseMenu.Tables[0].Columns.Contains("customVoce"))
				return baseMenu;
			if(customMenu==null) 
				return baseMenu;
			
			DataTable dt = baseMenu.Tables[0].Clone();
			dt.Columns["id"].DataType = typeof(string);
			dt.Columns["figliodi"].DataType = typeof(string);
			DataColumn dcCust = new DataColumn("customVoce");
			dcCust.DefaultValue=false;
			dcCust.DataType = typeof(bool);
			dt.Columns.Add(dcCust);
			dt.TableName = "CustomMenu";
			//intanto bisogna acquisire i valori dal sistema.
			for(int i = 0 ; i<baseMenu.Tables[0].Rows.Count; i++) {
				DataRow[] check = customMenu.Tables[0].Select("admin_menu='"+
				                                              baseMenu.Tables[0].Rows[i]["id"]
				                                              +"' and operation='R'");
				//il check permette l'esclusione dei valori RIMOSSI con selezione diretta.
				if(check.Length>0)  { 
					//trovi elementi da R bisogna verificare se si devono eliminare i figli di ID	
					CleanSons( baseMenu.Tables[0].Rows[i]["id"].ToString(), baseMenu);
					continue; 
				
				}
				DataRow[] check2 = customMenu.Tables[0].Select("admin_menu='"+
				                                              baseMenu.Tables[0].Rows[i]["figliodi"]
				                                              +"' and operation='R'");
				//il check permette l'esclusione dei valori RIMOSSI con selezione indiretta figli di...
				if(check2.Length>0) {
					//trovi elementi da R bisogna verificare se si devono eliminare i figli di ID											
					CleanSons( baseMenu.Tables[0].Rows[i]["figliodi"].ToString(), baseMenu);
					continue;
				}
				
				DataRow dr = dt.NewRow();
				for(int c = 0 ; c<baseMenu.Tables[0].Columns.Count; c++)
					dr[c] = baseMenu.Tables[0].Rows[i][c];
				dr["customVoce"] =false;
				dt.Rows.Add(dr);
				//controlla se ci sono figli:
				TryForSons(customMenu,dt,baseMenu.Tables[0].Rows[i]["id"].ToString(),lingua);
				/*
				DataRow[] evSons = customMenu.Tables[0].Select("operation='A' and sonof='"+baseMenu.Tables[0].Rows[i]["id"]+"' ");
				if(evSons.Length>0) {
					for(int s = 0 ; s<evSons.Length; s++) {
						DataRow drs = dt.NewRow();
						drs["id"] =(evSons[s]["customME"].ToString()=="0" && 
						            evSons[s]["id"].ToString()=="-1"
						            ?evSons[s]["admin_menu"]:("C"+evSons[s]["id"].ToString()));
						drs["link"] =evSons[s]["av_link"];
						drs["ruolo"] =evSons[s]["av_ruolo"];
						drs["enabled"] =evSons[s]["av_enabled"];
						//in questo caso il padre è il collegato.
						drs["figliodi"] =baseMenu.Tables[0].Rows[i]["id"];
						
						drs["ordine"] =evSons[s]["av_ordine"];
						drs["target"] =evSons[s]["av_target"];
						drs["lingua"] =(evSons[s]["av_lingua"]==null || 
				                evSons[s]["av_lingua"].ToString().Trim()=="" 
				                ?lingua:evSons[s]["av_lingua"]);
						drs["id_component"] =evSons[s]["av_id_component"];
						drs["urlimg"] =(evSons[s]["av_urlimg"]==null || 
				                evSons[s]["av_urlimg"].ToString().Trim()=="" 
				                ?"":evSons[s]["av_urlimg"]);
						drs["id_instance"] =evSons[s]["av_id_instance"];
						drs["name_group"] =(evSons[s]["av_name_group"]==null || 
				                evSons[s]["av_name_group"].ToString().Trim()=="" 
				                ?"":evSons[s]["av_name_group"]);
						drs["nome"] =(evSons[s]["customME"].ToString()=="0" && 
						              evSons[s]["id"].ToString()=="-1"
						              ?evSons[s]["av_nome"]:(evSons[s]["nomevoce"].ToString()));
						drs["customVoce"] =true;
						dt.Rows.Add(drs);
					
					}
				}
				*/
			}
			//aggiunta valori di tipo "A"
			DataRow[] mustAdd = customMenu.Tables[0].Select("operation='A' and sonof='-1' ");
			for(int s = 0 ; s<mustAdd.Length; s++) {
				DataRow drs = dt.NewRow();
				drs["id"] = (mustAdd[s]["customME"].ToString()=="0" && 
				             mustAdd[s]["id"].ToString()=="-1"
				             ?mustAdd[s]["admin_menu"]:("C"+mustAdd[s]["id"].ToString()));
				drs["link"] =mustAdd[s]["av_link"];
				drs["ruolo"] =mustAdd[s]["av_ruolo"];
				drs["enabled"] =mustAdd[s]["av_enabled"];
				drs["figliodi"] ="-1";
				drs["ordine"] =mustAdd[s]["av_ordine"];
				drs["target"] =mustAdd[s]["av_target"];
				drs["lingua"] =(mustAdd[s]["av_lingua"]==null || 
				                mustAdd[s]["av_lingua"].ToString().Trim()=="" 
				                ?lingua:mustAdd[s]["av_lingua"]);
				drs["id_component"] =mustAdd[s]["av_id_component"];
				drs["urlimg"] =(mustAdd[s]["av_urlimg"]==null || 
				                mustAdd[s]["av_urlimg"].ToString().Trim()=="" 
				                ?"":mustAdd[s]["av_urlimg"]);
				drs["id_instance"] =mustAdd[s]["av_id_instance"];
				drs["name_group"] =(mustAdd[s]["av_name_group"]==null || 
				                mustAdd[s]["av_name_group"].ToString().Trim()=="" 
				                ?"":mustAdd[s]["av_name_group"]);
				if(mustAdd[s]["operation"].ToString()=="A") {
					drs["nome"] = (mustAdd[s]["nomevoce"].ToString().Trim()==""?
					               mustAdd[s]["av_nome"]:(mustAdd[s]["nomevoce"].ToString()));
				} else {
					drs["nome"] =(mustAdd[s]["customME"].ToString()=="0" && 
				              mustAdd[s]["id"].ToString()=="-1"
				              ?mustAdd[s]["av_nome"]:(mustAdd[s]["nomevoce"].ToString()));
				}					
				drs["customVoce"] =true;
				dt.Rows.Add(drs);
				//verifica FIGLI RISPETTO NUOVO ID:
				TryForSons(customMenu,dt,drs["id"].ToString(),lingua);
				/*
				DataRow[] menuSons = customMenu.Tables[0].Select("operation='A' and sonof='"+drs["id"]+"' ");
				if(menuSons!=null && menuSons.Length>0) {
					for(int f =0; f<menuSons.Length; f++) {
						DataRow drf = dt.NewRow();
						drf["id"] = drs["id"].ToString() + (menuSons[f]["customME"].ToString()=="0" &&
						             menuSons[f]["id"].ToString()=="-1"
						             ?menuSons[f]["admin_menu"]:("C"+menuSons[f]["id"].ToString()));
						drf["link"] =menuSons[f]["av_link"];
						drf["ruolo"] =menuSons[f]["av_ruolo"];
						drf["enabled"] =menuSons[f]["av_enabled"];
						drf["figliodi"] =drs["id"];
						drf["ordine"] =menuSons[f]["av_ordine"];
						drf["target"] =menuSons[f]["av_target"];
						drf["lingua"] =(menuSons[f]["av_lingua"]==null || 
						                menuSons[f]["av_lingua"].ToString().Trim()=="" 
						                ?lingua:menuSons[f]["av_lingua"]);
						drf["id_component"] =menuSons[f]["av_id_component"];
						drf["urlimg"] =(menuSons[f]["av_urlimg"]==null || 
						                menuSons[f]["av_urlimg"].ToString().Trim()=="" 
						                ?"":menuSons[f]["av_urlimg"]);
						drf["id_instance"] =menuSons[f]["av_id_instance"];
						drf["name_group"] =(menuSons[f]["av_name_group"]==null || 
						                menuSons[f]["av_name_group"].ToString().Trim()=="" 
						                ?"":menuSons[f]["av_name_group"]);
						drf["nome"] =(menuSons[f]["customME"].ToString()=="0" && 
						              menuSons[f]["id"].ToString()=="-1"
						              ?menuSons[f]["av_nome"]:(menuSons[f]["nomevoce"].ToString()));
						drf["customVoce"] =true;
						dt.Rows.Add(drf);
					}
				}
				*/
				/*
				DataRow[] papa = baseMenu.Tables[0].Select("id = '"+mustAdd[s]["admin_menu"]+"' ");
				if(papa !=null && papa.Length>0)	{
					for(int cs = 0 ; cs<baseMenu.Tables[0].Columns.Count; cs++) {
						if(baseMenu.Tables[0].Columns[cs].ColumnName.ToLower()!="figliodi")
							drs[cs] = papa[0][cs];	
						else
							drs["figliodi"] = mustAdd[s]["sonof"];
					}
					drs["customVoce"] =true;
					dt.Rows.Add(drs);
				} else {
					drs["id"] = "C" + mustAdd[s]["id"];
					drs["nome"] = mustAdd[s]["nomevoce"];
					drs["figliodi"] = "-1";
					drs["ordine"] = "1";
					drs["customVoce"] =true;
					//aggiungi evetuali figli
					DataRow[] mustAddSons = customMenu.Tables[0].Select("operation='A' and sonof='C" + mustAdd[s]["id"]+"' ");
					for(int sN = 0 ; sN<mustAddSons.Length; sN++) {
						DataRow drson = dt.NewRow();
						DataRow[] papasons = baseMenu.Tables[0].Select("id = '"+mustAddSons[sN]["admin_menu"]+"' ");
						if(papasons !=null && papasons.Length>0)	{
							for(int cs = 0 ; cs<baseMenu.Tables[0].Columns.Count; cs++) {
								if(baseMenu.Tables[0].Columns[cs].ColumnName.ToLower()!="figliodi")
									drson[cs] = papasons[0][cs];	
								else
									drson["figliodi"] = mustAddSons[sN]["sonof"];
							}
							drson["customVoce"] =true;
							dt.Rows.Add(drson);							
						} else {
							drson["id"] = "C" + mustAddSons[sN]["id"];
							drson["nome"] = mustAddSons[sN]["nomevoce"];
							drson["figliodi"] = mustAddSons[sN]["sonof"];;
							drson["ordine"] = "1";
							drson["customVoce"] =true;
							dt.Rows.Add(drson);
							//throw new Exception("QUI CI SONO");						
						}
					}
					dt.Rows.Add(drs);
					//throw new Exception("QUI CI SONO");						
				}
				*/
			}
			baseMenu.Tables.Add(dt);
			baseMenu.Tables.RemoveAt(0);
			//HttpContext.Current.Session["adm_LayoutGAdminMenu_"+lingua] = baseMenu;
			return baseMenu;
		}
	
	
		public enum MenuModes {
			EditMode,
			List,
			Accordion
		}
		
		public string getMainMenu(string role, string score, string[] dep, string security,MenuModes menumode) {
			return getMainMenu(role, score,dep, security,menumode, "idMenu","");
		}
		public string getMainMenu(string role, string score, string[] dep, string security,MenuModes menumode,string idMenu) {
			return getMainMenu(role, score,dep, security,menumode, idMenu,"");
		}		
		public string getMainMenu(string role, string score, string[] dep, string security,MenuModes menumode, string idMenu,string lingua) {
			DataSet roleMenu = null;
			if(this.AdminMenu!=null) {
				roleMenu = AdminMenu;
			} else {
//				HttpContext.Current.Response.Write("SONO LA GENERAZIONE");
//				HttpContext.Current.Response.Write("OPZIONI CORRENTI: " +
//				                                   "ROLE: " + role + "<br/>" + 
//				                                   "score: " + score + "<br/>" + 
//				                                   "dep: " + string.Join(", ",dep) + "<br/>" +
//				                                   "sec: " + security + "<br/>" +
//				                                   "lang: " + lingua + "<br/>");
				//inizio calcolo del menu
				if(lingua=="") 
					roleMenu = processMenu(role,score,dep,security);
				else
					roleMenu = processMenu(role,score,dep,security,lingua);
				// fine calcolo del menu.
			}
			if(roleMenu==null) {
				return string.Empty;
			}
//			HttpContext.Current.Response.Write("SONO IL MENU UFF: " + roleMenu.GetXml() );
			if(roleMenu.Tables.Count == 0) return string.Empty;
			if(roleMenu.Tables[0].Rows.Count == 0) return string.Empty;
			//calcola il menu definitivo
			//qui bisogna solamente renderizzare il menu
			string menu = "";
			string qAdd = "";
			switch(menumode) {
				case MenuModes.List:
					qAdd = " AND ed_ckd<>'0' ";break;
				default: qAdd="";break;
			}
			DataRow[] Base = roleMenu.Tables[0].Select("(sonof='O-1' OR sonof='C-1') AND ed_eva='1' "+qAdd+"","ordine asc");
			for(int i = 0 ;i< Base.Length; i++) {
				
				switch(menumode) {
					case MenuModes.EditMode:
						menu+="<item>"+
					  "<id>" + Base[i]["mast_id"] + "</id>" +
					  "<link>" + Base[i]["link"] + "</link>" +
					  "<nome>" + Base[i]["nome"] + "</nome>"+
					  "<sonof>" + Base[i]["sonof"] + "</sonof>"+
					  "<order>" + Base[i]["ordine"] + "</order>"+							
					  "<checked>" + Base[i]["ed_ckd"] + "</checked>"+
					  "<ori-name>" + Base[i]["ori_name"] + "</ori-name>"+
					  "<ori-sonof>" + Base[i]["ori_sonof"] + "</ori-sonof>"+
					  "<ori-ckd>" + Base[i]["ori_ckd"] + "</ori-ckd>"+
					  "<ori-order>" + Base[i]["ori_order"] + "</ori-order>"+
					  "<lang>" + Base[i]["lingua"] + "</lang>";
//						HttpContext.Current.Response.Write(Base[i]["mast_id"] + "<br/>");
						menu+=getSonsMenu(roleMenu.Tables[0], Base[i]["mast_id"].ToString(),menumode);
						menu+="</item>";
						break;
					case MenuModes.List :
						if(Base[i]["nome"].ToString()=="#SEP#") continue;
						string sons = getSonsMenu(roleMenu.Tables[0], Base[i]["mast_id"].ToString(),menumode);
						if( Base[i]["link"] =="#" && sons == "") menu+=""; 
						else {
							string _link = Base[i]["link"].ToString();
							if(_link!="#") {
//								HttpContext.Current.Response.Write("MAIN: ["+Base[i]["nome"]+"]LINK " + _link + "<br/>");
								if(_link.IndexOf('?')!=-1)
									_link+=("&amp;idc=" +Base[i]["id_component"] +"&amp;idi=" + Base[i]["id_instance"]);
								else
									_link+=("?idc=" +Base[i]["id_component"] +"&amp;idi=" + Base[i]["id_instance"]);
							}
							string classzone = "";
							if(sons!="") {
								classzone = "class=\"MenuBarItemSubmenu "+Base[i]["cssclass"].ToString() + "\"";
							} else if ( Base[i]["cssclass"].ToString()!="") {
								classzone = "class=\""+(Base[i]["cssclass"].ToString()) + "\"";
							}							
							menu+="<li class=\"MainHome\"><a href=\""+_link +
								"\" "+classzone+" >" + Base[i]["nome"] + "</a>";
							menu+= sons;
							menu+="</li>";						
						}
						break;
				}

			}
			switch(menumode) {
				case MenuModes.EditMode:
					menu = "<menu>" + menu + "</menu>";break;
				case MenuModes.List:
					string id = "";
					if(string.IsNullOrEmpty(idMenu)) 
						id="";
					else if ( idMenu.Trim().Length==0)
						id ="";
					else
						id = "id=\"" + idMenu + "\"";
					menu ="<ul "+id+" class=\"MenuBarHorizontal\">" + menu + "</ul>";break;
			}
			return menu;
		}
		
		public DataSet getMainMenuDataSet(string role, string score, string[] dep, string security) {
			DataSet roleMenu = null;
			if(this.AdminMenu!=null) {
				roleMenu = AdminMenu;
			} else {
				//inizio calcolo del menu
				roleMenu = processMenu(role,score,dep,security);
				// fine calcolo del menu.
			}
			return roleMenu;
		}
		
#region RigheperilMenu
		void setAvaiable(DataTable dt, string padre, bool enable) {
			DataRow[] righe = dt.Select("sonof='"+padre+"' ","ordine asc");
			if(righe.Length==0) return ;
			for(int i =0;i<righe.Length;i++) {
				righe[i]["ed_eva"]=(enable?"1":"0");
				setAvaiable(dt,righe[i]["mast_id"].ToString(),enable);
			}
			return;
		}
		
		void setChecked(DataTable dt, string padre, bool enable) {
			DataRow[] righe = dt.Select("sonof='"+padre+"' ","ordine asc");
			if(righe.Length==0) return ;
			for(int i =0;i<righe.Length;i++) {
				if(righe[i]["directremove"].ToString()=="1") continue;
				righe[i]["ori_ckd"]=righe[i]["ed_ckd"];
				righe[i]["ed_ckd"]= (enable?"1":"0");
				setChecked(dt,righe[i]["mast_id"].ToString(),enable);
			}
			return;
		}		
		
		string getSonsMenu(DataTable dt,string padre, MenuModes menumodo) {
			string qAdd = "";
			switch(menumodo) {
				case MenuModes.List:
					qAdd = " AND ed_ckd<>'0' ";break;
				default: qAdd="";break;
			}	
	
			DataRow[] righe = dt.Select("sonof='"+padre+"' AND ed_eva='1' "+qAdd+" ","ordine asc");
			if(righe.Length==0) return "";
			string menu = string.Empty; //"<ul>";
			string s_menu = "";
			string e_menu = "";
			for(int i =0;i<righe.Length;i++) {
				switch(menumodo) {
					case MenuModes.EditMode:
						s_menu="<items>";
						e_menu="</items>";
						menu+="<item>"+
					    "<id>" + righe[i]["mast_id"] + "</id>" +
					    "<link>" + righe[i]["link"] + "</link>" +
					    "<nome>" + righe[i]["nome"] + "</nome>"+
						"<sonof>" + righe[i]["sonof"] + "</sonof>"+		
						"<order>" + righe[i]["ordine"] + "</order>"+
						"<checked>" + righe[i]["ed_ckd"] + "</checked>"+
					    "<ori-name>" + righe[i]["ori_name"] + "</ori-name>"+
					    "<ori-sonof>" + righe[i]["ori_sonof"] + "</ori-sonof>"+
					    "<ori-ckd>" + righe[i]["ori_ckd"] + "</ori-ckd>"+
					    "<ori-order>" + righe[i]["ori_order"] + "</ori-order>"+
						"<lang>" + righe[i]["lingua"] + "</lang>"+
						"<class>" + righe[i]["class"] + "</class>";
						menu+=getSonsMenu(dt, righe[i]["mast_id"].ToString(),menumodo);
						menu+="</item>";						
						break;
					case MenuModes.List:
						if(righe[i]["nome"].ToString()=="#SEP#") continue;
						string sons =  getSonsMenu(dt, righe[i]["mast_id"].ToString(),menumodo);
//						if(righe[i]["nome"].ToString().ToLower()=="articoli") 
//							HttpContext.Current.Response.Write("SONO SON: " + sons + ", LINK: "+ righe[i]["link"]);
					
						if(sons.Trim()=="" && righe[i]["link"].ToString().Trim()=="#") {
							menu+="";
							s_menu="";
							e_menu="";	
						} else {
							s_menu="<ul  "+(sons!=""?("class=\"MenuBarItems\""):"")+">";
							e_menu="</ul>";	
							string img ="";
							if(righe[i]["urlimg"].ToString().Trim().Length>0) {
								img ="<img src=\""+common_folder + righe[i]["urlimg"].ToString()+"\" " +
									"alt=\""+righe[i]["nome"]+"\" style=\"border:0px;\" />";
							}						
							string _link = righe[i]["link"].ToString();
							if(_link.Trim()!="#") {
//								HttpContext.Current.Response.Write("SONS: ["+righe[i]["nome"]+"]LINK " + _link + "<br/>");
								if(_link.IndexOf('?')!=-1)
									_link +=("&amp;idc=" +righe[i]["id_component"] +"&amp;idi=" + righe[i]["id_instance"]);
								else
									_link+= ("?idc=" +righe[i]["id_component"] +"&amp;idi=" + righe[i]["id_instance"]);
							}
							string classzone = "";
							if(sons!="") {
								classzone = "class=\"MenuBarItemSubmenu "+righe[i]["cssclass"].ToString() + "\"";
							} else if ( righe[i]["cssclass"].ToString()!="") {
								classzone = "class=\""+(righe[i]["cssclass"].ToString()) + "\"";
							}
							menu+="<li><a href=\""+_link+
								"\" " +classzone +
								">" + img + righe[i]["nome"] + "</a>";
							menu+= sons;
							menu+= "</li>";	
						}
						break;
						
				}
			}
			menu=s_menu + menu + e_menu;
			return menu;
		}

		private DataSet processMenu ( string role, string score, string[] dep, string security) {
				string lingua = "";
				if( ACM.cmsarea08.Users.CurrentUser !=null) {
					if(ACM.cmsarea08.Users.CurrentUser.Autorizzato) {
						lingua = ACM.cmsarea08.Users.CurrentUser.PrefLanguage;
					} else
						lingua = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
				} else 
					lingua = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;			
				return processMenu ( role, score, dep, security,lingua);
		}
		private DataSet processMenu ( string role, string score, string[] dep, string security,string lingua) {
				DataSet roleMenu = null;
			
				string[] dipolo = new string[0]; 
				if(dep[0]==role)
					dipolo = dep;
				else {
					dipolo = new string[dep.Length+1];
					dipolo[0] = role;
					dep.CopyTo(dipolo,1);
				}
				string wherefilt = "";
				//contenuti:
				if ( security.Substring(1,12).IndexOf('1')==-1) {
					wherefilt += " left(category,1)<>'C' and";	
				} else {
					if(security.Substring(1,4).IndexOf('1')==-1)
						wherefilt += " category<>'CS' and";
					if(security.Substring(4,4).IndexOf('1')==-1)
						wherefilt += " category<>'CC' and";
					if(security.Substring(8,4).IndexOf('1')==-1)
						wherefilt += " category<>'CA' and";
				}
				//template:
				if(security.Substring(13,3).IndexOf('1')==-1)
					wherefilt += " category<>'ST' and";
				//statistiche:
				if(security.Substring(17,1).IndexOf('1')==-1)
					wherefilt += " category<>'SS' and";
				//utenti:
				if ( security.Substring(17,8).IndexOf('1')==-1) {
					wherefilt += " left(category,1)<>'U' and";	
				} else {
					if(security.Substring(17,1).IndexOf('1')==-1)
						wherefilt += " category<>'UU' and";
					if(security.Substring(18,1).IndexOf('1')==-1)
						wherefilt += " category<>'UR' and";
					if(security.Substring(19,1).IndexOf('1')==-1)
						wherefilt += " category<>'UM' and";
					if(security.Substring(20,1).IndexOf('1')==-1)
						wherefilt += " category<>'UV' and";
				}
				//LAYOUT:
				if ( security.Substring(21,4).IndexOf('1')==-1) {
					wherefilt += " left(category,1)<>'L' and";	
				} else {
					if(security.Substring(21,1).IndexOf('1')==-1)
						wherefilt += " category<>'LH' and";
					if(security.Substring(22,1).IndexOf('1')==-1)
						wherefilt += " category<>'LB' and";
					if(security.Substring(23,1).IndexOf('1')==-1)
						wherefilt += " category<>'LM' and";
					if(security.Substring(24,1).IndexOf('1')==-1)
						wherefilt += " category<>'LV' and";
				}
				//PLUGINS:
				if(security.Substring(25,1).IndexOf('1')==-1)
					wherefilt += " category<>'PP' and";
				//LAYOUT:
				if ( security.Substring(26,3).IndexOf('1')==-1) {
					wherefilt += " left(category,1)<>'M' and";	
				} else {
					if(security.Substring(26,1).IndexOf('1')==-1)
						wherefilt += " category<>'MI' and";
					if(security.Substring(27,1).IndexOf('1')==-1)
						wherefilt += " category<>'MI' and";
					if(security.Substring(28,1).IndexOf('1')==-1)
						wherefilt += " category<>'MG' and";
				}
				//carica il menu del livello richiesto (e con il valore corretto)
				roleMenu = dclass.ExecuteDataset(
										string.Format(
										  "select distinct *, cast(concat('O',id) as char) as mast_id,cast(concat('O',figliodi) as char) as sonof, '1' as ed_eva, '1' as ed_ckd, " +
										  "'1' as ori_ckd, ordine as ori_order, nome as ori_name,cast(concat('O',figliodi) as char) as ori_sonof,'0' as directremove,'' as cssclass " +
										  "from {0}admin_menu " +
				                          "where {3} role_score>={2} and enabled='1' " +
				                          "and (lingua='{1}' or lingua='') order by figliodi,ordine ;",
				                          dclass.TablePrefix,lingua,score,wherefilt));

				if(roleMenu==null)
					return null;
				
				//pulizia valori in lingua:
				DataRow[] dLingua = roleMenu.Tables[0].Select("","id asc, lingua desc");
				DataRow[] dLingua2 = roleMenu.Copy().Tables[0].Select("","id asc, lingua desc");
				string currentID = string.Empty;
				bool removeNext = false;
				for(int i = 0; i<dLingua2.Length; i++) {
					
					if(currentID!=string.Empty || currentID.Trim()!="") {
						if(currentID==dLingua2[i]["id"].ToString().Trim() && removeNext==true) {
							//rimuovi riga.
							roleMenu.Tables[0].Rows.Remove(dLingua[i]);
							currentID ="";
							removeNext = false;
							continue;
						}
					}
					string cLingua = dLingua2[i]["lingua"].ToString().Trim();
					if(cLingua == lingua) {
						currentID= dLingua2[i]["id"].ToString().Trim();
						removeNext = true;
					} 
				}
				//get all permes
				DataSet dOp = null;
				if(dipolo.Length>0) {
					string qDip = "";
					foreach(string x in dipolo)
						qDip+=" relatedto='" +x+"' or";
					qDip = qDip.Substring(0,qDip.Length-2);
					dOp= dclass.ExecuteDataset("select * from "+ dclass.TablePrefix+"user_menu where ("+qDip+") and lang='"+lingua+"' ;");
					
//					HttpContext.Current.Response.Write(string.Format(
//					"select * from "+ dclass.TablePrefix+"user_menu where "+qDip+" ;"+"<hr>"));
					if(dOp==null && lingua !=ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita) {
						dOp= dclass.ExecuteDataset("select * from "+ dclass.TablePrefix+"user_menu where ("+qDip+") and lang='"+ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita+"' ;");
					}
				}		

				
				System.Array.Reverse(dipolo);
				
				if(dOp!=null) {
					int dipLength = dipolo.Length;
					for(int i = 0; i<dipLength; i++) {
						//prendi l'elenco dei custom.
						//prima lavora con tutte le R (ORIGINALI):
						DataRow[] dRem = dOp.Tables[0].Select(" relatedto='"+dipolo[i]+"' and operation='R' ");
						if(dRem!=null) {
							foreach(DataRow dr in dRem) {
									DataRow[] dSel = roleMenu.Tables[0].Select(" ed_eva<>'0' AND mast_id = 'O" + dr["admin_menu"].ToString() +"' ");
									foreach(DataRow dd in dSel) {
										dd["ordine"]=dr["order"];
										if(i == dipLength-1) {
											dd["ori_ckd"]=dd["ed_ckd"];
											dd["ed_ckd"]="0";
											dd["directremove"] = "1";
											setChecked(roleMenu.Tables[0],dd["mast_id"].ToString(),false);
										} else {
											dd["ed_eva"] = "0";
											setAvaiable(roleMenu.Tables[0],dd["mast_id"].ToString(),false);
										}
									}
							}
						}
						dRem = null;
						//Aggiunte
						dRem = dOp.Tables[0].Select(" relatedto='"+dipolo[i]+"' and operation='A' ");
						if(dRem!=null) {
							foreach(DataRow dr in dRem) {
								//aggiungi riga.
								DataRow dNew = roleMenu.Tables[0].NewRow();
								
								if(i == dipolo.Length-1) 
									dNew["mast_id"] = "newItem" +dr["id"].ToString();
								else
									dNew["mast_id"] = "C" +dr["id"].ToString();
								
								DataRow[] dSel = roleMenu.Tables[0].Select(" mast_id = 'O" + dr["admin_menu"].ToString() +"' ");
								if(dSel.Length>0) {
									dNew["link"] = dSel[0]["link"];
									dNew["ori_name"] = dSel[0]["nomevoce"].ToString();
									dNew["nome"] =  dSel[0]["nomevoce"].ToString();
								} else 
									dNew["link"] = (dr["suffixurl"].ToString()!=""?dr["suffixurl"].ToString():"#");
								
								string sonof = (dr["sonof"].ToString()=="-1"?"O-1":dr["sonof"].ToString());								
								dNew["nome"] = dr["nomevoce"].ToString();
								dNew["ori_name"] = dr["nomevoce"].ToString();
								dNew["enabled"]="1";
								if(dr["relatedto"].ToString().Trim()==role.Trim() ) {
									if(sonof.StartsWith("C"))
										sonof = sonof.Replace("C","newItem");
								}
								dNew["sonof"]= sonof;
								dNew["ori_sonof"] = dNew["sonof"];
								dNew["ordine"]=dr["order"];							
								dNew["ori_order"]=dNew["ordine"];							
								dNew["lingua"]=dr["lang"];
								dNew["ed_eva"]="1";
								dNew["ed_ckd"]="1";
								dNew["ori_ckd"]="1";
								dNew["cssclass"]=(dr["class"].ToString()!=""?dr["class"].ToString():"");
								
								roleMenu.Tables[0].Rows.Add(dNew);
							}
						}					
						
						dRem = null;
						//Spostamenti
						dRem = dOp.Tables[0].Select(" relatedto='"+dipolo[i]+"' and operation='S' ");
						if(dRem!=null) {
							foreach(DataRow dr in dRem) {
								string sonof = dr["sonof"].ToString();
								if(i == dipLength-1) {
									string testSonOf = sonof.Replace("O","");
									testSonOf = testSonOf.Replace("C","");
									DataRow[] testCurrent = dOp.Tables[0].Select(" relatedto='"+dipolo[dipLength-1]+"' " +
									                                             "and operation='A' " +
									                                             "and id=" + testSonOf );
									if(testCurrent!=null && testCurrent.Length>0)
										sonof = sonof.Replace("C","newItem");
								}
								//aggiungi riga.
								DataRow[] dSel = roleMenu.Tables[0].Select(" mast_id = 'O" + dr["admin_menu"].ToString() +"' ");
								foreach(DataRow dd in dSel) {
									dd["ori_sonof"] = dd["sonof"];
									//cambio:
									dd["sonof"] = sonof; //dr["sonof"];
									dd["ori_name"]  = dd["nome"].ToString();
									dd["nome"]  = dr["nomevoce"].ToString();
									dd["ori_order"]  = dd["ordine"].ToString();
									dd["ordine"]  = dr["order"].ToString();
									dd["ed_eva"] = "1";
									dd["ori_ckd"]=dd["ed_ckd"];
									dd["ed_ckd"] = "1";
									setChecked(roleMenu.Tables[0],dd["mast_id"].ToString(),true);
								}
								dSel = null;
								dSel = roleMenu.Tables[0].Select(" mast_id = 'C" + dr["id"].ToString() +"' ");
								foreach(DataRow dd in dSel) {
									dd["ori_sonof"] = dd["sonof"];
									dd["sonof"] = sonof; //dr["sonof"];
									dd["ori_name"]  = dd["nome"].ToString();
									dd["nome"]  = dr["nomevoce"].ToString();
									dd["ori_order"]  = dd["ordine"].ToString();
									dd["ordine"]  = dr["order"].ToString();
									dd["ed_eva"] = "1";
									dd["ori_ckd"]=dd["ed_ckd"];
									dd["ed_ckd"] = "1";
									setChecked(roleMenu.Tables[0],dd["mast_id"].ToString(),true);
								}
								dSel = null;
								dSel = roleMenu.Tables[0].Select(" mast_id = 'newItem" + dr["id"].ToString() +"' ");
								foreach(DataRow dd in dSel) {
									dd["ori_sonof"] = dd["sonof"];
									dd["sonof"] = sonof; //dr["sonof"];
									dd["ori_name"]  = dd["nome"].ToString();
									dd["nome"]  = dr["nomevoce"].ToString();
									dd["ori_order"]  = dd["ordine"].ToString();
									dd["ordine"]  = dr["order"].ToString();
									dd["ed_eva"] = "1";
									dd["ori_ckd"]=dd["ed_ckd"];
									dd["ed_ckd"] = "1";
									setChecked(roleMenu.Tables[0],dd["mast_id"].ToString(),true);
								}	
								dSel = null;
								dSel = roleMenu.Tables[0].Select(" mast_id = '" + dr["admin_menu"].ToString() +"' ");
								foreach(DataRow dd in dSel) {
									dd["ori_sonof"] = dd["sonof"];
									dd["sonof"] = sonof; //dr["sonof"];
									dd["ori_name"]  = dd["nome"].ToString();
									dd["nome"]  = dr["nomevoce"].ToString();
									dd["ori_order"]  = dd["ordine"].ToString();
									dd["ordine"]  = dr["order"].ToString();
									dd["ed_eva"] = "1";
									dd["ori_ckd"]=dd["ed_ckd"];
									dd["ed_ckd"] = "1";
									setChecked(roleMenu.Tables[0],dd["mast_id"].ToString(),true);
								}								
							}
						}	
						dRem = null;
						//DUPLICATI: 
						dRem = dOp.Tables[0].Select(" relatedto='"+dipolo[i]+"' and operation='D' ");
						if(dRem!=null) {
							foreach(DataRow dr in dRem) {
								DataRow[] dSel = roleMenu.Tables[0].Select(" mast_id = 'O" + dr["admin_menu"].ToString() +"' ");
								string linko = "";
								string id_component = "";
								string id_instance  = "";
								foreach(DataRow dd in dSel) {
									linko = dd["link"].ToString();
									id_component = dd["id_component"].ToString();
									id_instance  = dd["id_instance"].ToString();
								}							
								
								//HttpContext.Current.Response.Write("<br/>TROVO DUPLICATO: " + dr["nomevoce"]);
								//trovo i duplicati..quindi aggiungo all'array originale?
								DataRow dNew = roleMenu.Tables[0].NewRow();
								if(i == dipLength-1) 
									dNew["mast_id"] = "newItem" +dr["id"].ToString();
								else
									dNew["mast_id"] = "C" +dr["id"].ToString();
								
								dNew["nome"] = dr["nomevoce"].ToString();
								dNew["ori_name"] = dr["nomevoce"].ToString();
								dNew["link"] = linko + "" + dr["suffixUrl"];
//								HttpContext.Current.Response.Write("SUFF: " + dr["suffixUrl"] + "<br/>");
								dNew["id_component"] =id_component;
								dNew["id_instance"] =id_instance;
								dNew["enabled"]="1";
								string sonof = (dr["sonof"].ToString()=="-1"?"O-1":dr["sonof"].ToString());
								dNew["sonof"]= sonof;
								dNew["ori_sonof"] = dNew["sonof"];
								dNew["ordine"]=dr["order"];							
								dNew["ori_order"]=dNew["ordine"];							
								dNew["lingua"]=dr["lang"];
								dNew["ed_eva"]="1";
								dNew["ed_ckd"]="1";
								dNew["ori_ckd"]="1";
								roleMenu.Tables[0].Rows.Add(dNew);
							}
						}
						
						
						//prima lavora con tutte le R (CUSTOM):
						dRem = dOp.Tables[0].Select(" relatedto='"+dipolo[i]+"' and operation='R' ");
						if(dRem!=null) {
							foreach(DataRow dr in dRem) {
									DataRow[] dSel = roleMenu.Tables[0].Select(" ed_eva<>'0' AND mast_id = '" + dr["admin_menu"].ToString() +"' ");
									foreach(DataRow dd in dSel) {
										dd["ordine"]=dr["order"];
										if(i==dipLength-1) {
											dd["ori_ckd"]=dd["ed_ckd"];
											dd["ed_ckd"] = "0";
											setChecked(roleMenu.Tables[0],dd["mast_id"].ToString(),false);
										} else {
											dd["ed_eva"] = "0";
											setAvaiable(roleMenu.Tables[0],dd["mast_id"].ToString(),false);
										}
									}
							}
						}
						dRem = null;
					}
				}
				System.Array.Reverse(dipolo);
				return roleMenu;
		}
		
#endregion	
	}
}
